const NeedLogin = require('../need_login.js');
const fs = require('fs');
const path = require('path');
const ffmpeg = require('fluent-ffmpeg');
var ffprobe = think.promisify(ffmpeg.ffprobe, ffmpeg)


const captureImageOne = (video, cover)=> {
  return new Promise((reslove, reject) => {
    try {
      ffmpeg(video)
        .on('filenames', (filenames)=> {
          console.log(filenames);
        }).on('end', ()=> {
          reslove(cover);
        }).screenshots({
          timestamps: ['00:01.000'],
          folder: path.dirname(cover),
          filename: path.basename(cover)
        });
      } catch(err) { reject(err) }
  })
}

module.exports = class extends NeedLogin {
  async indexAction() {
    var OSS = this.model('oss').useOSS();
    try {
      let result = await OSS.put('test/2019/04/02/sadasdasd.jpg', this.file('files').path);
      console.log(result)
    } catch (e) {
      console.log(e);
    }
  }
  async videoAction() { // 视频上传
    var db = this.mongoose('mongo/sn_upload'); // 链接数据库
    try {
      if (this.file('files') instanceof Array) {
        return this.json({status: -2, msg: '视频不支持批量上传'})
      } else {
        if (this.file('files').type.indexOf('video/') !== 0) {
          return this.json({status: -2, msg: '不是正确的视频格式'})
        }
        var maxSize = 50
        if (this.file('files').size > (1048576 * maxSize)) {
          return this.json({status: -2, msg: '视频最大' + maxSize + 'M'})
        }
        think.mkdir(path.join(
          think.ROOT_PATH, 'www', 'upload',
          think.datetime(new Date()).substr(0,4),think.datetime(new Date()).substr(5,2),think.datetime(new Date()).substr(8,2)
        ))// 创建文件夹
        var videoPath = path.join(
          'upload' ,think.datetime(new Date()).substr(0,4),think.datetime(new Date()).substr(5,2),think.datetime(new Date()).substr(8,2),
          think.uuid('v1') + path.extname(this.file('files').path)
        )
        var coverPath = path.join(
          'upload' ,think.datetime(new Date()).substr(0,4),think.datetime(new Date()).substr(5,2),think.datetime(new Date()).substr(8,2),
          think.uuid('v1') + '.jpg'
        )
        var _videoPath = path.join(think.ROOT_PATH, 'www', videoPath)
        var _coverPath = path.join(think.ROOT_PATH, 'www', coverPath)
        fs.renameSync(this.file('files').path, _videoPath)
        var _videoDb = new db({
          uid: this.post('uid'),
          path: _videoPath,
          url: videoPath
        })
        var videoDb = await _videoDb.save();
        await captureImageOne(_videoPath, _coverPath)
        var _coverDb = new db({
          uid: this.post('uid'),
          path: _coverPath,
          url: coverPath
        })
        var coverDb = await _coverDb.save();
        var fileInfo = await ffprobe(_videoPath)
        var videoInfo = {
          cover: coverDb._id,
          url: videoDb._id,
          width: fileInfo.streams[0].width,
          height: fileInfo.streams[0].height,
          duration: fileInfo.streams[0].duration
        }
        this.json({
          status: 1,
          result: videoInfo
        })
      }
    } catch (e) {
      this.json({
        status: -1,
        msg: e.message
      })
    }
  }
  async imageAction() { // 图片上传
    var db = this.mongoose('mongo/sn_upload'); // 链接数据库
    try {
      var files = []
      if (!(this.file('files') instanceof Array)) {
        files.push(this.file('files'))
      } else {
        files = this.file('files')
      }
      if (files.length > 9) return this.json({status: -2,msg: '最多上传9张图片'})
      // 循环验证图片是否符合要求
      files.some((item) => {
        if (item.type.indexOf('image/') !== 0) {
          this.json({status: -2, msg: '不是正确的图片格式'})
          return true
        }
        var maxSize = 10
        if (item.size > (1048576 * maxSize)) {
          this.json({status: -2, msg: '单张图片最大' + maxSize + 'M'})
          return true
        }
      })
      // 循环保存图片
      var imgList = []
      for(var i = 0; i < files.length; i++) { // 循环文件数组
        think.mkdir(path.join(
          think.ROOT_PATH, 'www', 'upload',
          think.datetime(new Date()).substr(0,4),think.datetime(new Date()).substr(5,2),think.datetime(new Date()).substr(8,2)
        )) // 创建文件夹
        var path1 = path.join(
          'upload' ,think.datetime(new Date()).substr(0,4),think.datetime(new Date()).substr(5,2),think.datetime(new Date()).substr(8,2),
          think.uuid('v1') + path.extname(files[i].path)
        )
        var newpath = path.join(think.ROOT_PATH, 'www', path1)
        fs.renameSync(files[i].path, newpath)
        let filedb = new db({
          path: newpath,url: path1,uid: this.post('uid')
        }); //创建数据库文档
        var result = await filedb.save();
        var fileInfo = await ffprobe(newpath)
        var imginfo = {
          url: result._id,
          width: fileInfo.streams[0].width,
          height: fileInfo.streams[0].height
        }
        imgList.push(imginfo)
      }
      this.json({
        status: 1,
        result: imgList
      })
    } catch (e) {
      this.json({
        status: -1,
        msg: e.message
      })
    }
  }
  async audioAction() { // 语音上传
    var db = this.mongoose('mongo/sn_upload'); // 链接数据库
    try {
      if (this.file('files') instanceof Array) {
        return this.json({status: -2, msg: '音频不支持批量上传'})
      }
      var files = this.file('files')
      if (files.type.indexOf('audio/') !== 0) {
        this.json({status: -2, msg: '不是正确的音频格式'})
        return true
      }
      var maxSize = 20
      if (files.size > (1048576 * maxSize)) {
        this.json({status: -2, msg: '音频最大' + maxSize + 'M'})
        return true
      }

      think.mkdir(path.join(
        think.ROOT_PATH, 'www', 'upload',
        think.datetime(new Date()).substr(0,4),think.datetime(new Date()).substr(5,2),think.datetime(new Date()).substr(8,2)
      )) // 创建文件夹
      var path1 = path.join(
        'upload' ,think.datetime(new Date()).substr(0,4),think.datetime(new Date()).substr(5,2),think.datetime(new Date()).substr(8,2),
        think.uuid('v1') + path.extname(files.path)
      )
      var newpath = path.join(think.ROOT_PATH, 'www', path1)
      fs.renameSync(files.path, newpath)
      let filedb = new db({
        path: newpath,url: path1,uid: this.post('uid')
      }); //创建数据库文档
      var result = await filedb.save();
      var fileInfo = await ffprobe(newpath)
      var info = {
        url: result._id,
        duration: fileInfo.streams[0].duration
      }
      this.json({
        status: 1,
        result: info
      })
    } catch (e) {
      this.json({
        status: -1,
        msg: e.message
      })
    }
  }
};
